<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px">
      <el-form-item label="项目" prop="grantId">
        <el-select v-model="queryParams.grantId" placeholder="请选择项目">
          <el-option
            v-for="dict in grantOptions"
            :key="dict.grantId"
            :label="dict.grantName"
            :value="dict.grantId"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="createPlan"
        >生成</el-button>
      </el-col>

        <el-col :span="1.5">
          <el-button
            type="success"
            icon="el-icon-edit"
            size="mini"
            @click="handleImport"
            v-hasPermi="['grant:companyplan:export']"
          >导入计划数</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="primary"
            icon="el-icon-crop"
            size="mini"
            @click="listSelfPlan"
          >本单位计划</el-button>
        </el-col>
        <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['grant:companyplan:export']"
        >导出分派结果</el-button>
      </el-col>
         <el-col :span="1.5">
          <el-button
            type="primary"
            icon="el-icon-download"
            size="mini"
            @click="exportListSelfPlan"
          >导出本单位计划</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="mini"
            @click="showConfigCel=true"
          >列设置</el-button>
        </el-col>
      <el-col :span="1.5">
        <el-button
          type="delete"
          icon="el-icon-plus"
          size="mini"
          @click="deleteGrCompanyPlanByComId"
        >删除派出单位计划</el-button>
      </el-col>
    </el-row>
    <div class="itemTrading">
    <el-table v-loading="loading" :data="companyplanList" @selection-change="handleSelectionChange"  :cell-style="cellStyle" show-summary stripe>
      <template v-for='item in fieldList'>
        <el-table-column :label="item.value" :prop="item.key" :key="item.key" v-if="showcelstrs==''||showcelstrs.indexOf(';'+item.key+';')>=0"
                         :fixed="item.key === 'comId' ? true : false"
        >
        </el-table-column>
      </template>
    </el-table>
    </div>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
<!--查看本单位计划弹窗-->
    <el-dialog :title="title" :visible.sync="selfOpen" width="1024px" append-to-body>
      <el-table v-loading="loading" :data="selfPlanList">
        <template v-for='item in selfFieldList'>
          <el-table-column :label="item.value" :prop="item.key" :key="item.key" v-if="showcelstrs==''||showcelstrs.indexOf(';'+item.key+';')>=0">
          </el-table-column>
        </template>
      </el-table>
    </el-dialog>
    <!-- 添加或修改派出单位计划管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="项目" prop="grantId">
          <el-input v-model="form.grantId" placeholder="请输入项目" />
        </el-form-item>
        <el-form-item label="派出单位" prop="companyId">
          <el-input v-model="form.companyId" placeholder="请输入派出单位" />
        </el-form-item>
        <el-form-item label="科类" prop="subjectCode">
          <el-input v-model="form.subjectCode" placeholder="请输入科类" />
        </el-form-item>
        <el-form-item label="计划数" prop="planNum">
          <el-input v-model="form.planNum" placeholder="请输入计划数" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 计划数对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?grantId=' + queryParams.grantId"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          <el-link type="info" style="font-size:12px" @click="importTemplate">下载模板</el-link>
        </div>
        <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！
          <br></br>在导出文件的基础上，直接填入相关计划数后，原文件导入即可。
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
    <el-drawer
      title="设置列"
      :visible.sync="showConfigCel"
      :direction="direction"
      :size="'900px'"
    >
      <div class="querywhere">
        <el-checkbox-group v-model="configshowcel" size="small">
          <el-checkbox
            border
            v-for="(item, index) in fieldList"
            :key="item.key"
            :label="item.key"
            >{{ item.value }}</el-checkbox
          >
        </el-checkbox-group>
        <el-button type="info" @click="configshowcel = []">清空</el-button>
        <el-button type="primary" @click="showConfigCel = false;handleQuery();">确认</el-button>
        <el-button type="primary" @click="onlySelectPlan">只选计划</el-button>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import {  getCompanyplan, delCompanyplan, addCompanyplan, updateCompanyplan, exportCompanyplan,createComapnyPlan,listSelfPlan,exportPlanForSubject,getCompanyPlanForSubject,exportForSubject,getCompanyPlanForSubjectSelf,deleteGrCompanyPlanByComId } from "@/api/grant/companyplan";
import {listGrantAll} from "@/api/grant/grant";
import {getToken} from "@/utils/auth";

export default {
  name: "Companyplan",
  data() {
    return {
      // 遮罩层
      loading: true,
      showConfigCel:false,
      configshowcel: [],
      showcelstrs:'',
      direction: 'rtl',
      // 选中数组
      ids: [],
      grantOptions: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      totalself: 0,
      // 派出单位计划管理表格数据
      companyplanList: [],
      showCompanyplanList: [],
      fieldList:[],
      selfPlanList:[],
      selfFieldList:[],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      selfOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        grantId: undefined,
        companyId: undefined,
        subjectCode: undefined,
        planNum: undefined,
        isExportTemplate:'N',
        configshowcelSearch: undefined
      },
      selfParams:{
        pageNum: 1,
        pageSize: 10,
        grantId: undefined,
        companyId: undefined,
        subjectCode: undefined,
        planNum: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      // 计数数导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "计划导入",
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/grant/companyplan/importComapnyPlanForSubject"
      }
    };
  },
  created() {
    let query ={};
    query["isEnabled"]="0";
    listGrantAll(query).then(res=>{
      this.grantOptions = res.data;
      this.queryParams.grantId=res.data[res.data.length-1].grantId;
      this.getList();
    })
  },
  methods: {
    /** 查询派出单位计划管理列表 */
    getList() {
      this.loading = true;
      this.queryParams.isExportTemplate = 'N';
      getCompanyPlanForSubject(this.queryParams).then(response => {
        this.companyplanList = response.data["ROWMAPLIST"];
        this.fieldList = response.data["FIELDMAP"];
        if(this.configshowcel.length == 0)
        {
          for(let ni=0;ni<this.fieldList.length;ni++)
           {
              this.configshowcel.push(this.fieldList[ni].key);
           }
          this.showCompanyplanList = response.data["FIELDMAP"];
          this.showcelstrs = ';'+this.configshowcel.join(";")+';';
        }else
        {
           this.showcelstrs = ';'+this.configshowcel.join(";")+';';
           for(let ni=0;ni<this.fieldList.length;ni++)
           {
              if(this.showcelstrs.indexOf(this.fieldList[ni].key+';')>=0){
                this.showCompanyplanList.push(this.fieldList[ni]);
              }
           }
        }
        // console.log(this.configshowcel);
        // console.log(this.configshowcel.join(","));
        this.loading = false;
      });
    },
    listSelfPlan(){
      this.selfOpen = true;
      this.selfParams = this.queryParams
      this.loading = true;
      getCompanyPlanForSubjectSelf(this.selfParams).then(response => {
        this.selfPlanList = response.data["ROWMAPLIST"];
        this.selfFieldList = response.data["FIELDMAP"];
        this.loading = false;

      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        grantId: undefined,
        companyId: undefined,
        subjectCode: undefined,
        planNum: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加派出单位计划管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getCompanyplan(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改派出单位计划管理";
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            updateCompanyplan(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }
            });
          } else {
            addCompanyplan(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除派出单位计划管理编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delCompanyplan(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      queryParams.isExportTemplate='N';
      queryParams.configshowcelSearch = this.configshowcel.join(",");
      this.$confirm('是否确认导出所有派出单位计划管理数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {

          return exportForSubject(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function() {});
    },
    /** 导出本单位计划操作 */
    exportListSelfPlan() {
      const queryParams = this.queryParams;
      queryParams.isExportTemplate='Y';
      queryParams.configshowcelSearch = this.configshowcel.join(",");
      this.$confirm('是否确认导出本单位派出计划?', "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportPlanForSubject(queryParams);
        }).then(response => {
          this.download(response.msg);
        }).catch(function() {});
    },
    importTemplate(){
      const queryParams = this.queryParams;
      queryParams.isExportTemplate='Y';
      queryParams.configshowcelSearch = this.configshowcel.join(",");
      this.$confirm('是否确认导出计划数模版?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return exportForSubject(queryParams);
      }).then(response => {
        this.download(response.msg);
      }).catch(function() {});
    },
    /**生成初始计划数据 **/
    createPlan(){
      const createData = {};
      createData['grantId'] = this.queryParams.grantId;

      createComapnyPlan(createData).then(response=>{
        if (response.code === 200) {
          this.msgSuccess("生成成功");
          this.open = false;
          this.getList();
        }
      })
    },    /** 导入 按钮操作 */
    handleImport() {
      this.upload.title = "派出单位计划导入";
      this.upload.open = true;
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      //导出失败的记录
      if(response.data!=null)
      {
        this.exportExcel(response.data)
      }
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    cellStyle(row,column,rowIndex,columnIndex){
      if(row.columnIndex%2==1){
        return "background:rgb(201, 218, 248)";
      }
    },
    onlySelectPlan(){
      this.configshowcel = [];
      for(let ni=0;ni<this.fieldList.length;ni++)
      {
        if(this.fieldList[ni].value.indexOf("报名数")<0){
          this.configshowcel.push(this.fieldList[ni].key);
        }
      }
    },
    deleteGrCompanyPlanByComId(){
      const deleteData = {};
      deleteData['grantId'] = this.queryParams.grantId;
      this.$confirm('是否要清除已生成计划?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return deleteGrCompanyPlanByComId(deleteData).then();
      }).then(()=>{
        this.msgSuccess("删除成功");
        this.open = false;
        this.getList();
      }).catch(function() {});
    }
  }
};
</script>
<style>
.itemTrading .el-table{
  overflow: auto;
}
.itemTrading  .el-table__body-wrapper,
.itemTrading  .el-table__header-wrapper,
.itemTrading  .el-table__footer-wrapper {
  overflow: visible;
}
.itemTrading  .el-table::after {
  position: relative !important;
}
  .body-theme-grenn .el-table--scrollable-x .el-table__body-wrapper{
    overflow: visible;
  }
  .querywhere {
  margin: 5px;
}
.el-drawer.rtl{
    overflow: scroll;
}
.querywhere >>> .el-checkbox.is-bordered.el-checkbox--small {
  padding: 8px;
  width: 122px;
}
.querywhere >>> .el-checkbox.is-bordered + .el-checkbox.is-bordered {
  margin-left: 0px;
}
.querywhere >>> .el-checkbox {
  margin-right: 10px;
}
</style>
